package com.sky.exception;

import com.sky.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 全局异常处理类
 * @author 尹稳健~
 * @version 1.0
 * @time 2022/8/13
 */
@SuppressWarnings({"all","unchecked"})
@RestControllerAdvice
@Slf4j
public class GlobalException {

    @ExceptionHandler(value = BindException.class)
    public R exceptionHandle(BindException exception) {
        BindingResult result = exception.getBindingResult();
        StringBuilder errorMsg = new StringBuilder();
        List<FieldError> fieldErrors = result.getFieldErrors();
        fieldErrors.forEach(error -> {
            log.error("field: " + error.getField() + ", msg:" + error.getDefaultMessage());
            errorMsg.append(error.getDefaultMessage()).append("!");
        });
        return R.fail(errorMsg.toString());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R<Object> constraintViolationExceptionHandler(MethodArgumentNotValidException exception) {
        BindingResult result = exception.getBindingResult();
        StringBuilder errorMsg = new StringBuilder();
        List<FieldError> fieldErrors = result.getFieldErrors();
        fieldErrors.forEach(error -> {
            log.error("field: " + error.getField() + ", msg:" + error.getDefaultMessage());
            errorMsg.append(error.getDefaultMessage()).append("!");
        });
        return R.fail(errorMsg.toString());
    }

    // 处理运行时异常
    @ExceptionHandler(RuntimeException.class)
    public R doHandleRuntimeException(RuntimeException e) {
        e.printStackTrace();
        return R.fail(e.getMessage());
    }

    // 自定义基础异常处理类
    @ExceptionHandler(BaseException.class)
    public R doHandleBaseException(RuntimeException e) {
        e.printStackTrace();
        return R.fail(e.getMessage());
    }

    // 处理运行时异常
    @ExceptionHandler(Exception.class)
    public R doHandleException(Exception e) {
        e.printStackTrace();
        return R.fail("系统业务错误！");
    }
}
